package com.czy.owner.ui.illegalquery;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.ProvinceCodeAdapter;
import com.czy.owner.adapter.ProvinceCodeCharAdapter;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.entity.CityModel;
import com.czy.owner.entity.FrameNumberModel;
import com.czy.owner.entity.IllegalQueryDetailModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.IllegalEvent;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.archive.TakeFrameFrament;
import com.czy.owner.ui.archive.TakeFrameNumberActivity;
import com.czy.owner.ui.garage.CarUtils;
import com.czy.owner.utils.GsonUtils;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SoftKeyBoardListener;
import com.czy.owner.utils.StringUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by wangyang on 2016/12/8 0008.
 * 违章查询
 * 皖ABR690
 * //    VIN 078647
 * //    发动机 838561
 */
public class IllegalQueryActivity extends BaseActivity {
    private Dialog guideDialog;
    @BindView(R.id.tv_province)
    TextView tvProvince;
    @BindView(R.id.tv_province_code)
    TextView tvProvinceCode;
    @BindView(R.id.et_license_plate)
    EditText etCarCode;
    @BindView(R.id.tv_prompt)
    TextView tvPrompt;

    @BindView(R.id.tv_body_num)
    TextView tvBodyNum;
    @BindView(R.id.et_body_num)
    EditText etBody;
    @BindView(R.id.iv_body_num)
    ImageView ivBodyNum;

    @BindView(R.id.tv_engine_num)
    TextView tvEngineNum;
    @BindView(R.id.et_engine_num)
    EditText etEngine;
    @BindView(R.id.iv_engine_num)
    ImageView ivEngineNum;
    @BindView(R.id.rv_province_code)
    EasyRecyclerView rvProvinceCode;

    private CityModel model = null;
    private List<String> cityProvince = new ArrayList<>();


    private int frameno = -1;
    private int engineno = -1;
    private String carorg;

    private CarInfo carInfo;
    private boolean isGarage;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_illegal_query;
    }

    @Override
    protected void initInjector() {
        carInfo = (CarInfo) getIntent().getSerializableExtra("carInfo");
        isGarage = getIntent().getBooleanExtra("isGarage", false);
               /*註冊*/
        RxBus.getDefault().register(this);
    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText("查询信息");
        CarUtils.ShowNumber(IllegalQueryActivity.this, rvProvinceCode, etCarCode);
        CarUtils.etChangeListener(etCarCode, rvProvinceCode);
        getViolationCities();

        etCarCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                etCarCode.removeTextChangedListener(this);
                etCarCode.setText(s.toString().toUpperCase());
                etCarCode.setSelection(s.toString().length());
                etCarCode.addTextChangedListener(this);

            }

            @Override
            public void afterTextChanged(Editable s) {
                String carCode = tvProvinceCode.getText().toString();
                if (TextUtils.isEmpty(carCode)) {
                    etCarCode.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
                } else {
                    etCarCode.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
                }
                if (carInfo != null && !(tvProvince.getText().toString().trim() + tvProvinceCode.getText().toString().trim() + carCode).equals(carInfo.getLicenseNumber())) {
                    tvPrompt.setVisibility(View.GONE);
                }
            }
        });


        SoftKeyBoardListener.setListener(IllegalQueryActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {

            }

            @Override
            public void keyBoardHide(int height) {
                rvProvinceCode.setVisibility(View.GONE);
                etCarCode.clearFocus();

            }
        });
        if (carInfo != null) {
            tvProvince.setText(carInfo.getLicenseNumber().substring(0, 1));
            tvProvinceCode.setText(carInfo.getLicenseNumber().substring(1, 2));
        }
        illegalCity(tvProvince.getText().toString().trim(), tvProvinceCode.getText().toString().trim(), isGarage);
    }

    @Override
    protected void updateViews() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (TakeFrameFrament.SCANNING_FRAME_REQUESTCODE == requestCode && TakeFrameFrament.SCANNING_FRAME_RESULTCODE == resultCode) {
            FrameNumberModel frameNumberModel = (FrameNumberModel) data.getSerializableExtra(TakeFrameFrament.SCANNING_FRAME_INTENT);
            if (frameno > 0) {
                etBody.setText(frameNumberModel.getVin().substring(frameno == 100 ? 0 : frameNumberModel.getVin().length() - frameno, frameNumberModel.getVin().length()));
            } else {
                etBody.setText(frameNumberModel.getVin());
            }
        }
    }

    /*接受事件*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(IllegalEvent changeText) {
        if ("1".equals(changeText.getType()) || "2".equals(changeText.getType()))
            finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
                  /*註冊*/
        RxBus.getDefault().unRegister(this);
    }


    //省
    private void getViolationCities() {
        mLoadView.ShowLoadView();
        String Url = Constants.APP_API_BASE + Constants.PUB_GET_VIOLATION_CITIES;
        RequestParams params = new RequestParams(Url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(IllegalQueryActivity.this).getSession());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                try {
                    if (flag) {
                        Gson gson = new Gson();
                        model = gson.fromJson(result, CityModel.class);
                        cityProvince.clear();
                        for (int i = 0; i < model.getData().size(); i++) {
                            if (!TextUtils.isEmpty(model.getData().get(i).getShorthand())) {
                                cityProvince.add(model.getData().get(i).getShorthand());
                            }
                        }


                    } else {
                        PhoneUtils.ShowToastMessage(IllegalQueryActivity.this, exp);
                    }
                } catch (Exception e) {
                    MyLog.e("yang", "e==" + e.toString());
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    //省Dialog
    private void showProvinceDialog() {
        // 定义Dialog布局和参数
        final Dialog dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_province_code, null);
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        // 设置Dialog最小宽度为屏幕宽度
        view.setMinimumWidth(display.getWidth());

        // 获取自定义Dialog布局中的控件
        RecyclerView rvProvinceCode = (RecyclerView) view.findViewById(R.id.rv_province_code);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 7);
        rvProvinceCode.setLayoutManager(layoutManager);
        ProvinceCodeAdapter mAdapter = new ProvinceCodeAdapter(this, cityProvince, tvProvince.getText().toString().trim());
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object o, View view) {
                if ("港澳台".indexOf(o.toString()) != -1) {
                    PhoneUtils.ShowToastMessage(IllegalQueryActivity.this, "暂不支持港澳台地区违章查询！");
                    return;
                }
                tvProvince.setText((String) o);
                if (dialog != null) {
                    dialog.dismiss();
                }
                etCarCode.setFocusable(true);
                etCarCode.setFocusableInTouchMode(true);
                illegalCity(tvProvince.getText().toString().trim(), tvProvinceCode.getText().toString().trim(), false);
                showProvinceCode();

            }
        });
        rvProvinceCode.setAdapter(mAdapter);
        RecycleViewDivider mDivider = new RecycleViewDivider(this, 3, R.drawable.shape_recyclerview_divider_decoration);
        mDivider.setSpanCount(7);
        rvProvinceCode.addItemDecoration(mDivider);

        dialog.setContentView(view);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.LEFT | Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.x = 0;
        lp.y = 0;
        dialogWindow.setAttributes(lp);
        dialog.show();
    }

    //市Dialog
    private void showProvinceCode() {
        // 定义Dialog布局和参数
        final Dialog dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        List<String> listCode = new ArrayList<>();
        for (char i = 'A'; i <= 'Z'; i++) {
            listCode.add(i + "");
        }
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_province_code, null);
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        // 设置Dialog最小宽度为屏幕宽度
        view.setMinimumWidth(display.getWidth());
        // 获取自定义Dialog布局中的控件
        RecyclerView rvProvinceCode = (RecyclerView) view.findViewById(R.id.rv_province_code);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 7);
        rvProvinceCode.setLayoutManager(layoutManager);
        ProvinceCodeCharAdapter mAdapter = new ProvinceCodeCharAdapter(this, listCode, tvProvinceCode.getText().toString().trim());
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object o, View view) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                tvProvinceCode.setText((String) o);

                illegalCity(tvProvince.getText().toString().trim(), tvProvinceCode.getText().toString().trim(), false);
            }
        });
        rvProvinceCode.setAdapter(mAdapter);
        RecycleViewDivider mDivider = new RecycleViewDivider(this, 3, R.drawable.shape_recyclerview_divider_decoration);
        mDivider.setSpanCount(7);
        rvProvinceCode.addItemDecoration(mDivider);

        dialog.setContentView(view);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.LEFT | Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.x = 0;
        lp.y = 0;
        dialogWindow.setAttributes(lp);
        dialog.show();
    }

    //    frameno和engineno 根据管局需要输入（100为全部输入，0为不输入）
//    车牌号：91k56
//    车架号：084527
//    发动机号：562189
//    获取交管局参数
    private void illegalCity(String lsprefix, String lsnum, final boolean bool) {
        //当车牌号信息被修改时提示是否隐藏
        if (carInfo != null && !(tvProvince.getText().toString().trim() + tvProvinceCode.getText().toString().trim() + etCarCode.getText().toString()).equals(carInfo.getLicenseNumber())) {
            tvPrompt.setVisibility(View.GONE);
        }
        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.PUB_ILLEGALCITY);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(IllegalQueryActivity.this).getSession());
        params.addBodyParameter("lsprefix", lsprefix);
        params.addBodyParameter("lsnum", lsnum);
        MyLog.e("yang", "params==" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);
                String data = PhoneUtils.checkResponseFlag(IllegalQueryActivity.this, result);
                if (data != null) {
                    frameno = JsonUtil.getJsonValuesInt(data, "frameno");
                    engineno = JsonUtil.getJsonValuesInt(data, "engineno");
                    carorg = JsonUtil.getJsonValuesString(data, "carorg");
                    changeEditext(frameno, engineno);
                    if (bool) {
                        setEditData();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }


    //    frameno和engineno 根据管局需要输入（100为全部输入，0为不输入）
    private void changeEditext(int frameno, int engineno) {
        etEngine.setText("");
        etBody.setText("");
        if (frameno > 0 && frameno != 100) {
            tvBodyNum.setEnabled(true);
            etBody.setFilters(new InputFilter[]{new InputFilter.LengthFilter(frameno)});
            etBody.setEnabled(true);
            ivBodyNum.setEnabled(true);
            etBody.setHint("请输入车架号后" + frameno + "位");
        } else if (frameno == 0) {
            tvBodyNum.setEnabled(false);
            etBody.setEnabled(false);
            ivBodyNum.setEnabled(false);
            etBody.setHint("请输入车架号");
        } else {
            tvBodyNum.setEnabled(true);
            etBody.setEnabled(true);
            ivBodyNum.setEnabled(true);
            etBody.setHint("请输入合法的车架号");
        }


        if (engineno > 0 && engineno != 100) {
            tvEngineNum.setEnabled(true);
            etEngine.setFilters(new InputFilter[]{new InputFilter.LengthFilter(engineno)});
            etEngine.setEnabled(true);
            ivEngineNum.setEnabled(true);
            etEngine.setHint("请输入发动机号后" + engineno + "位");
        } else if (engineno == 0) {
            tvEngineNum.setEnabled(false);
            etEngine.setEnabled(false);
            ivEngineNum.setEnabled(false);
            etEngine.setHint("请输入发动机号");
        } else {
            tvEngineNum.setEnabled(true);
            etEngine.setEnabled(true);
            ivEngineNum.setEnabled(true);
            etEngine.setHint("请输入合法的发动机号");

        }


    }

    public void setEditData() {
        etEngine.setText("");
        etBody.setText("");
        etCarCode.setText(carInfo.getLicenseNumber().substring(2, carInfo.getLicenseNumber().length()));
        if (!StringUtils.isEmpty(carInfo.getChassisNumber()) && frameno > 0) {
            etBody.setText(carInfo.getChassisNumber().substring(frameno == 100 ? 0 : carInfo.getChassisNumber().length() - frameno, carInfo.getChassisNumber().length()));
        }
        if (!StringUtils.isEmpty(carInfo.getEngineType()) && engineno > 0) {
            etEngine.setText(carInfo.getEngineType().substring(engineno == 100 ? 0 : carInfo.getEngineType().length() - engineno, carInfo.getEngineType().length()));
        }
        if (StringUtils.isEmpty(carInfo.getChassisNumber()) && frameno != 0) {
            tvPrompt.setVisibility(View.VISIBLE);
        }
        if (StringUtils.isEmpty(carInfo.getEngineType()) && engineno != 0) {
            tvPrompt.setVisibility(View.VISIBLE);
        }
    }


    @OnClick(R.id.btn_query)
    public void btnQueryOnClick(View view) {
        String province = tvProvince.getText().toString().trim();
        String licenseNumber = etCarCode.getText().toString().trim();
        String bodyNum = etBody.getText().toString().trim();
        String engineNum = etEngine.getText().toString();

        if (TextUtils.isEmpty(province)) {
            PhoneUtils.ShowToastMessage(IllegalQueryActivity.this, "请选择省份");
            return;
        }


        if (TextUtils.isEmpty(licenseNumber)) {
            PhoneUtils.ShowToastMessage(IllegalQueryActivity.this, "车牌号码不能为空");
            return;
        }


        if (licenseNumber.length() < 5) {
            PhoneUtils.ShowToastMessage(IllegalQueryActivity.this, "车牌号码不合法");
            return;
        }

//        if (!PhoneUtils.checkLicensePlate(tvProvinceCode.getText().toString() + licenseNumber)) {
//            PhoneUtils.ShowToastMessage(IllegalQueryActivity.this, "车牌号码不合法");
//            return;
//        }

        if (frameno != 0 && frameno != -1 && frameno != 100) {
            if (TextUtils.isEmpty(bodyNum) || (bodyNum.length() != frameno)) {
                PhoneUtils.ShowToastMessage(IllegalQueryActivity.this, "请输入车架号后" + frameno + "位");
                etBody.requestFocus();
                return;

            }
        } else if (frameno == 100) {
            if (!PhoneUtils.checkVINisLegal(engineNum)) {
                PhoneUtils.ShowToastMessage(IllegalQueryActivity.this, "请正确输入车架号");
                etBody.requestFocus();
                return;
            }
        } else if (frameno == -1) {
            if (TextUtils.isEmpty(bodyNum)) {
                PhoneUtils.ShowToastMessage(IllegalQueryActivity.this, "请输入合法的车架号");
                etBody.requestFocus();
                return;

            }
        }


        if (engineno != 0 && engineno != -1 && engineno != 100) {
            if (TextUtils.isEmpty(engineNum) || engineNum.length() != engineno) {
                PhoneUtils.ShowToastMessage(IllegalQueryActivity.this, "请输入发动机号后" + engineno + "位");
                etEngine.requestFocus();
                return;
            }
        } else if (engineno == -1 || engineno == 100) {
            if (TextUtils.isEmpty(engineNum)) {
                PhoneUtils.ShowToastMessage(IllegalQueryActivity.this, "请输入合法的发动机号");
                etEngine.requestFocus();
                return;
            }
        }

        StringBuilder licenseNumberStr = new StringBuilder();
        licenseNumberStr.append(province + tvProvinceCode.getText().toString().trim() + licenseNumber);

//        参数名	必选	类型	说明
//        session	是	string	登录返回的session
//        lsprefix	是	string	车牌号首字母 （皖）
//        lsnum	是	string	车牌号后6位 （A12345）
//        carorg	是	string	城市 （hefei） 通过交管局获取
//        engineno	是	string	发动机号 长度通过交管局获取
//        frameno	是	string	车架号 长度通过交管局获取

        getQueryLLLegalList(tvProvince.getText().toString().trim(), tvProvinceCode.getText().toString() + licenseNumber, carorg, etEngine.getText().toString().trim(), etBody.getText().toString().trim());


    }
//


    private void getQueryLLLegalList(String lsprefix, String lsnum, String carorg, String engineno, String frameno) {
        mLoadView.ShowLoadView();
        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.PUB_QUERYLLLEGAL);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(IllegalQueryActivity.this).getSession());
        params.addBodyParameter("lsprefix", lsprefix);
        params.addBodyParameter("lsnum", lsnum);
        params.addBodyParameter("carorg", carorg);
        params.addBodyParameter("engineno", engineno);
        params.addBodyParameter("frameno", frameno);
        boolean isTemporary = true;
        if (isGarage && carInfo.getLicenseNumber().equals(lsprefix + lsnum)) {
            isTemporary = false;
            Log.i("hedepu", String.valueOf(isTemporary));
        }
        params.addBodyParameter("isTemporary", String.valueOf(isTemporary));
        MyLog.e("yang", "params==" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                RxBus.getDefault().post(new IllegalEvent("3"));
                if (flag) {

                    String mData = JsonUtil.getJsonValuesString(result, "data");
                    List<IllegalQueryDetailModel> list = new ArrayList<>();
                    list.clear();
                    list = GsonUtils.fromJsonList(mData, IllegalQueryDetailModel.class);
                    Intent ti = new Intent(IllegalQueryActivity.this, IllegalQueryDetailActivity.class);
                    ti.putExtra("list", (Serializable) list);
                    startActivity(ti);
                    finish();
                } else {
                    PhoneUtils.ShowToastMessage(IllegalQueryActivity.this, exp);
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }


    private void showVehicleTips() {
        if (guideDialog == null) {
            guideDialog = new Dialog(this, R.style.AlertDialogStyle);
            ImageView mImageView = new ImageView(this);
            mImageView.setImageResource(R.mipmap.icon_vin_guide);
            guideDialog.setContentView(mImageView);
            guideDialog.setCancelable(true);
            guideDialog.setCanceledOnTouchOutside(true);

            Window dialogWindow = guideDialog.getWindow();
            WindowManager.LayoutParams p = dialogWindow.getAttributes();
            WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            Display mDisplay = windowManager.getDefaultDisplay();
            p.width = (int) (mDisplay.getWidth() * 0.86);
            dialogWindow.setAttributes(p);
        }
        guideDialog.show();

    }

    @OnClick(R.id.line_province_code)
    public void lineProvinceCodeOnClick(View view) {
        showProvinceDialog();
    }

    @OnClick(R.id.iv_body_num)
    public void ivVehicleTip1OnClick(View view) {
        showVehicleTips();
    }

    @OnClick(R.id.iv_engine_num)
    public void ivVehicleTip2OnClick(View view) {
        showVehicleTips();
    }

    @OnClick(R.id.linear_scanning)
    public void ivScaningClick(View view) {

        startActivityForResult(new Intent(IllegalQueryActivity.this, TakeFrameNumberActivity.class), TakeFrameFrament.SCANNING_FRAME_REQUESTCODE);
    }


}
